import {defineStore} from "pinia";
import store from "@/store/store";
import {login} from "@/api/login/login";
import tagStore from "@/store/tag";
import {
  appinit,
  deepClone,
  makeRoutes,
  removeAuthInfo,
  setAuthInfo
} from "@/utils/common";
import {getLoginUser, userInfo} from "@/api/common";

const useUserStore = defineStore("userStore", {
  state() {
    return {
      //用户基本个人信息
      userInfo: {} as any,
      //登录信息 例如权限
      autnInfo: {} as any,
      //菜单
      authMenus: [] as any
    };
  },
  actions: {
    login(data) {
      //账号密码登录
      return new Promise((resolve, reject) => {
        login(data)
          .then((res) => {
            setAuthInfo(res.data);
            appinit();
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    logout() {
      //退出
      return new Promise((resolve, reject) => {
        // logoutApi().then(res => {
        //     removeAuthInfo()
        //     resolve(res)
        // }).catch(err => {
        //     reject(err)
        // })
        setTimeout(() => {
          removeAuthInfo();
          tagStore.visitData = [];
          resolve("success");
        }, 300);
      });
    },
    getUserInfo() {
      //获取基本用户信息
      return new Promise((resolve, reject) => {
        userInfo()
          .then((res) => {
            this.userInfo = res.data;
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    async getLoginUser() {
      let res = await getLoginUser();
      this.autnInfo = res.data;
      this.authMenus = res.data.menus;
      let routes = await makeRoutes(deepClone(res.data.menus));
      return {
        routes
      };
    }
  }
});

export default useUserStore(store);
